// pages/tools/tools.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // QR码生成器
    qrText: '',
    qrCodeUrl: '',
    
    // 单位转换器
    convertFrom: 1,
    convertFromUnit: 'm2',
    convertToUnit: 'hectare',
    convertResult: '0.0001',
    currentUnitType: 'area', // 当前单位类型
    fromUnitIndex: 0,
    toUnitIndex: 1,
    
    // 价格计算器
    price: 0,
    quantity: 1,
    discount: 0,
    tax: 6, // 税率6%
    totalPrice: 0,
    
    // 所有单位选项
    unitTypes: {
      area: [
        { value: 'm2', label: '平方米 (㎡)' },
        { value: 'hectare', label: '公顷 (ha)' },
        { value: 'acre', label: '亩' },
        { value: 'km2', label: '平方公里 (km²)' },
        { value: 'ft2', label: '平方英尺 (ft²)' }
      ],
      length: [
        { value: 'm', label: '米 (m)' },
        { value: 'km', label: '公里 (km)' },
        { value: 'cm', label: '厘米 (cm)' },
        { value: 'mm', label: '毫米 (mm)' },
        { value: 'inch', label: '英寸 (in)' },
        { value: 'ft', label: '英尺 (ft)' }
      ],
      weight: [
        { value: 'kg', label: '千克 (kg)' },
        { value: 'g', label: '克 (g)' },
        { value: 'ton', label: '吨 (t)' },
        { value: 'lb', label: '磅 (lb)' },
        { value: 'oz', label: '盎司 (oz)' }
      ],
      temperature: [
        { value: 'celsius', label: '摄氏度 (°C)' },
        { value: 'fahrenheit', label: '华氏度 (°F)' },
        { value: 'kelvin', label: '开尔文 (K)' }
      ]
    },

    // 当前单位类型的单位选项
    currentUnits: [],
    
    // 常用转换快捷按钮
    commonConversions: [],

    // 当前选中的单位显示文本
    fromUnitLabel: '平方米 (㎡)',
    toUnitLabel: '公顷 (ha)'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initConverter()
    this.calculatePrice()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // QR码生成
  generateQRCode() {
    if (!this.data.qrText.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }

    // 使用微信小程序的API生成二维码
    const qrText = encodeURIComponent(this.data.qrText)
    const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrText}`
    
    this.setData({
      qrCodeUrl
    })
  },

  // 保存二维码
  saveQRCode() {
    if (!this.data.qrCodeUrl) {
      wx.showToast({
        title: '请先生成二维码',
        icon: 'none'
      })
      return
    }

    wx.downloadFile({
      url: this.data.qrCodeUrl,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            })
          },
          fail: () => {
            wx.showToast({
              title: '保存失败',
              icon: 'error'
            })
          }
        })
      }
    })
  },

  // 初始化转换器
  initConverter() {
    const currentUnits = this.data.unitTypes[this.data.currentUnitType]
    const commonConversions = this.getCommonConversions(this.data.currentUnitType)
    
    this.setData({
      currentUnits,
      commonConversions
    })
    
    this.convertUnits()
  },

  // 获取常用转换
  getCommonConversions(unitType) {
    const conversions = {
      area: [
        { id: 1, value: 1, from: 'm2', to: 'hectare', fromLabel: '㎡→ha', toLabel: '' },
        { id: 2, value: 100, from: 'm2', to: 'acre', fromLabel: '㎡→亩', toLabel: '' },
        { id: 3, value: 1, from: 'hectare', to: 'acre', fromLabel: 'ha→亩', toLabel: '' }
      ],
      length: [
        { id: 1, value: 1, from: 'm', to: 'km', fromLabel: 'm→km', toLabel: '' },
        { id: 2, value: 1, from: 'm', to: 'cm', fromLabel: 'm→cm', toLabel: '' },
        { id: 3, value: 1, from: 'ft', to: 'inch', fromLabel: 'ft→in', toLabel: '' }
      ],
      weight: [
        { id: 1, value: 1, from: 'kg', to: 'g', fromLabel: 'kg→g', toLabel: '' },
        { id: 2, value: 1, from: 'ton', to: 'kg', fromLabel: 't→kg', toLabel: '' },
        { id: 3, value: 1, from: 'kg', to: 'lb', fromLabel: 'kg→lb', toLabel: '' }
      ],
      temperature: [
        { id: 1, value: 0, from: 'celsius', to: 'fahrenheit', fromLabel: '°C→°F', toLabel: '' },
        { id: 2, value: 100, from: 'celsius', to: 'fahrenheit', fromLabel: '°C→°F', toLabel: '' },
        { id: 3, value: 273.15, from: 'celsius', to: 'kelvin', fromLabel: '°C→K', toLabel: '' }
      ]
    }
    
    return conversions[unitType] || []
  },

  // 单位转换
  convertUnits() {
    const { convertFrom, convertFromUnit, convertToUnit, currentUnitType } = this.data
    
    if (!convertFrom || convertFrom === '') {
      this.setData({ convertResult: '0' })
      return
    }
    
    let result = 0
    const value = parseFloat(convertFrom)

    // 面积转换 (基准单位：平方米)
    const areaConversions = {
      'm2': 1,
      'hectare': 0.0001,
      'acre': 0.00015,
      'km2': 0.000001,
      'ft2': 10.764
    }

    // 长度转换 (基准单位：米)
    const lengthConversions = {
      'm': 1,
      'km': 0.001,
      'cm': 100,
      'mm': 1000,
      'inch': 39.3701,
      'ft': 3.28084
    }

    // 重量转换 (基准单位：千克)
    const weightConversions = {
      'kg': 1,
      'g': 1000,
      'ton': 0.001,
      'lb': 2.20462,
      'oz': 35.274
    }

    // 温度转换 (特殊处理)
    if (currentUnitType === 'temperature') {
      result = this.convertTemperature(value, convertFromUnit, convertToUnit)
    } else {
      let conversions = {}
      
      switch (currentUnitType) {
        case 'area':
          conversions = areaConversions
          break
        case 'length':
          conversions = lengthConversions
          break
        case 'weight':
          conversions = weightConversions
          break
      }

      if (conversions[convertFromUnit] && conversions[convertToUnit]) {
        const baseValue = value / conversions[convertFromUnit]
        result = baseValue * conversions[convertToUnit]
      }
    }

    // 格式化结果
    let formattedResult = ''
    if (result === 0) {
      formattedResult = '0'
    } else if (Math.abs(result) >= 1000000) {
      formattedResult = result.toExponential(4)
    } else if (Math.abs(result) < 0.0001 && result !== 0) {
      formattedResult = result.toExponential(4)
    } else {
      formattedResult = result.toFixed(6).replace(/\.?0+$/, '')
    }

    this.setData({
      convertResult: formattedResult
    })
  },

  // 温度转换
  convertTemperature(value, fromUnit, toUnit) {
    if (fromUnit === toUnit) return value

    let celsius = value
    
    // 转换为摄氏度
    if (fromUnit === 'fahrenheit') {
      celsius = (value - 32) * 5 / 9
    } else if (fromUnit === 'kelvin') {
      celsius = value - 273.15
    }
    
    // 从摄氏度转换为目标单位
    if (toUnit === 'fahrenheit') {
      return celsius * 9 / 5 + 32
    } else if (toUnit === 'kelvin') {
      return celsius + 273.15
    }
    
    return celsius
  },

  // 价格计算
  calculatePrice() {
    const { price, quantity, discount, tax } = this.data
    
    const subtotal = price * quantity
    const discountAmount = subtotal * (discount / 100)
    const afterDiscount = subtotal - discountAmount
    const taxAmount = afterDiscount * (tax / 100)
    const total = afterDiscount + taxAmount

    this.setData({
      totalPrice: total.toFixed(2)
    })
  },

  // 输入事件处理
  onQRTextInput(e) {
    this.setData({
      qrText: e.detail.value
    })
  },

  onConvertFromInput(e) {
    this.setData({
      convertFrom: parseFloat(e.detail.value) || 0
    })
    this.convertUnits()
  },

  onPriceInput(e) {
    this.setData({
      price: parseFloat(e.detail.value) || 0
    })
    this.calculatePrice()
  },

  onQuantityInput(e) {
    this.setData({
      quantity: parseFloat(e.detail.value) || 1
    })
    this.calculatePrice()
  },

  onDiscountInput(e) {
    this.setData({
      discount: parseFloat(e.detail.value) || 0
    })
    this.calculatePrice()
  },

  onTaxInput(e) {
    this.setData({
      tax: parseFloat(e.detail.value) || 0
    })
    this.calculatePrice()
  },

  // 单位选择
  onFromUnitChange(e) {
    const index = e.detail.value
    const selectedUnit = this.data.currentUnits[index]
    if (selectedUnit) {
      this.setData({
        convertFromUnit: selectedUnit.value,
        fromUnitLabel: selectedUnit.label,
        fromUnitIndex: index
      })
      this.convertUnits()
    }
  },

  onToUnitChange(e) {
    const index = e.detail.value
    const selectedUnit = this.data.currentUnits[index]
    if (selectedUnit) {
      this.setData({
        convertToUnit: selectedUnit.value,
        toUnitLabel: selectedUnit.label,
        toUnitIndex: index
      })
      this.convertUnits()
    }
  },

  // 复制结果
  copyResult(e) {
    const type = e.currentTarget.dataset.type
    let text = ''

    switch (type) {
      case 'convert':
        text = `${this.data.convertFrom} ${this.data.fromUnitLabel} = ${this.data.convertResult} ${this.data.toUnitLabel}`
        break
      case 'price':
        text = `总价: ¥${this.data.totalPrice}`
        break
    }

    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  },

  // 重置功能
  resetQR() {
    this.setData({
      qrText: '',
      qrCodeUrl: ''
    })
  },

  // 切换单位类型
  switchUnitType(e) {
    const unitType = e.currentTarget.dataset.type
    const currentUnits = this.data.unitTypes[unitType]
    const commonConversions = this.getCommonConversions(unitType)
    
    // 重置为该类型的默认单位
    const defaultFromUnit = currentUnits[0]
    const defaultToUnit = currentUnits[1] || currentUnits[0]
    
    this.setData({
      currentUnitType: unitType,
      currentUnits,
      commonConversions,
      convertFromUnit: defaultFromUnit.value,
      convertToUnit: defaultToUnit.value,
      fromUnitLabel: defaultFromUnit.label,
      toUnitLabel: defaultToUnit.label,
      fromUnitIndex: 0,
      toUnitIndex: 1,
      convertFrom: 1
    })
    
    this.convertUnits()
  },

  // 交换单位
  swapUnits() {
    const { convertFromUnit, convertToUnit, fromUnitLabel, toUnitLabel, fromUnitIndex, toUnitIndex, convertResult } = this.data
    
    this.setData({
      convertFromUnit: convertToUnit,
      convertToUnit: convertFromUnit,
      fromUnitLabel: toUnitLabel,
      toUnitLabel: fromUnitLabel,
      fromUnitIndex: toUnitIndex,
      toUnitIndex: fromUnitIndex,
      convertFrom: parseFloat(convertResult) || 0
    })
    
    this.convertUnits()
  },

  // 快速转换
  quickConvert(e) {
    const { from, to, value } = e.currentTarget.dataset
    const currentUnits = this.data.currentUnits
    
    // 找到对应的单位索引
    const fromIndex = currentUnits.findIndex(unit => unit.value === from)
    const toIndex = currentUnits.findIndex(unit => unit.value === to)
    
    if (fromIndex !== -1 && toIndex !== -1) {
      this.setData({
        convertFrom: parseFloat(value),
        convertFromUnit: from,
        convertToUnit: to,
        fromUnitLabel: currentUnits[fromIndex].label,
        toUnitLabel: currentUnits[toIndex].label,
        fromUnitIndex: fromIndex,
        toUnitIndex: toIndex
      })
      
      this.convertUnits()
    }
  },

  // 分享结果
  shareResult() {
    const { convertFrom, fromUnitLabel, convertResult, toUnitLabel } = this.data
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    // 这里可以设置分享的内容
    this.shareContent = `单位转换结果：${convertFrom} ${fromUnitLabel} = ${convertResult} ${toUnitLabel}`
  },

  resetConverter() {
    // 重置为当前类型的默认值
    const currentUnits = this.data.currentUnits
    const defaultFromUnit = currentUnits[0]
    const defaultToUnit = currentUnits[1] || currentUnits[0]
    
    this.setData({
      convertFrom: 1,
      convertFromUnit: defaultFromUnit.value,
      convertToUnit: defaultToUnit.value,
      fromUnitLabel: defaultFromUnit.label,
      toUnitLabel: defaultToUnit.label,
      fromUnitIndex: 0,
      toUnitIndex: 1
    })
    this.convertUnits()
  },

  resetCalculator() {
    this.setData({
      price: 0,
      quantity: 1,
      discount: 0,
      totalPrice: 0
    })
    this.calculatePrice()
  }
})